import { WebSocket } from "ws";
import { Server } from "../../socket/Server";
import { BridgeConnection } from "../../socket/connection/BridgeConnection";
import { InnerMsg, InnerMsgType, InnerServer } from "../../socket/ClientServer";
import { InnerProtocol, L2B_Server } from "../../proto/innerMsg";



/**
 * 中间服务器
 */
export class BridgeServer extends Server<BridgeConnection> {
    private _serverMap: Map<InnerServer, BridgeConnection> = new Map();

    onconnect(ws: WebSocket): void {
        const connection = new BridgeConnection(ws);
        connection.onMsg = this.onMsg.bind(this);
        this._connections.push(connection);
    }


    onMsg(connection: BridgeConnection, cmd: number, data: InnerMsg) {
        if (cmd == InnerProtocol.SERVER) {
            const body: L2B_Server = data.body
            this._serverMap.set(body.serverId, connection)
            data.type = InnerMsgType.BACK
            connection.sendData(cmd, data)
            return;
        }
        if (!this._serverMap.has(InnerServer.LOBBY) || !this._serverMap.has(InnerServer.GAME)) {
            return;
        }

        if (data.type == InnerMsgType.PUSH) {
            this._serverMap.forEach((v, k) => {
                if (data.from != k) {
                    v.sendData(cmd, data)
                }
            })
            return
        }
        this._serverMap.get(data.to!)!.sendData(cmd, data);
    }
}


